package com.geek.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.entity.User;
import com.geek.factory.mapper.UserMapper;
import com.geek.factory.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.utils.JwtUtil;
import com.geek.factory.utils.POIUtils;
import com.geek.factory.vo.PageQueryVO;
import com.geek.factory.vo.UserQueryVO;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
@Transactional(readOnly = true)
@Override
public User login(UserQueryVO vo) {
    if(ObjectUtils.isEmpty(vo)){
        return null;
    }
    String username = vo.getUsername();
    String password = vo.getPassword();
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(StringUtils.hasLength(username) , User::getUsername , username);
    lambdaQueryWrapper.eq(StringUtils.hasLength(password) , User::getPassword , password);
    //查询
    User user = baseMapper.selectOne(lambdaQueryWrapper);
    return user;
}
    @Transactional(readOnly = true)
    @Override
    public Page<User> page(PageQueryVO vo) {
        Integer now = vo.getCurrentPage();
        Integer size = vo.getPageSize();
        //分页条件
        Page<User> page = new Page<>(now , size);

        //封装查询条件
        String query = vo.getQueryString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(query) , User::getUsername , query);

        //调用自定义Mapper接口的方法
        Page<User> userPage = userMapper.selectAllPage(page , wrapper);
        return userPage;
    }

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String loginByPhone(String phone) {
        User user = userMapper.selectByPhone(phone);
        if (user == null)
            return null;
        return jwtUtil.createToken(Long.valueOf(user.getId()), user.getPhone());
    }
    @Override
    public User getOneByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }


    @Override
    public boolean upload(MultipartFile excelFile) throws IOException {
        if(excelFile!=null){
            //从上传的Excel文件中读取数据
            //String[] account=0:账户 username=1:用户名 password=2:密码
            List<String[]> strings = POIUtils.readExcel(excelFile);
            //List<String[]> -> List<User>
            List<User> users =
                    strings.stream().map(strs -> {
                        User user = new User();
                        user.setAccount(strs[0]);
                        user.setUsername(strs[1]);
                        user.setPassword(strs[2]);
                        user.setStatus(1); // 默认启用
                        user.setRoleId(2); // 默认普通用户角色
                        user.setCreateTime(LocalDateTime.now());
                        return user;
                    }).collect(Collectors.toList());

            //遍历用户列表，若用户名不存在则插入数据，若存在则更新数据
            users.forEach(this::edit);
            return true;
        }
        return false;
    }

    private void edit(User user) {
        //封装查询条件，查询用户名是否已存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User existingUser = baseMapper.selectOne(wrapper);

        if(existingUser != null){
            //更新数据，保留原有的role_id
            user.setRoleId(existingUser.getRoleId());
            baseMapper.update(user, wrapper);
        }else{
            //插入数据
            baseMapper.insert(user);
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=user_template.xlsx");

        //创建Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表
        XSSFSheet sheet = workbook.createSheet("用户导入模板");
        //创建表头
        XSSFRow row = sheet.createRow(0);
        String[] headers = {"账号", "用户名", "密码"};
        for (int i = 0; i < headers.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
        }

        //写入示例数据
        XSSFRow dataRow = sheet.createRow(1);
        String[] example = {"155698898", "哆啦A梦", "admin123456"};
        for (int i = 0; i < example.length; i++) {
            XSSFCell cell = dataRow.createCell(i);
            cell.setCellValue(example[i]);
        }

        //自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        //写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
